import React from 'react';
import { Form, Modal, Select, InputNumber, DatePicker, message } from 'antd';
import moment from 'moment/moment';
import { delayTask, delayTaskDetail } from '../../../services';
import { TimeFormatForm, TimeFormatHour, TimeFormat } from '../../../utils';
import { FORM_DEFAULT_LAYOUT, MODAL_DEFAULT_PARAM, MODAL_FORCE_PARAM } from '../config';
import FileFormItem from './components/FileFormItem';
import LimitedTextArea from '../../../components/LimitedTextArea';
import styles from './index.less';

const { Option } = Select;
const DelayFormModal = ({ form, taskRecord, visible, setVisible, onOk }) => {
    const { id = undefined } = taskRecord;
    const { getFieldDecorator, validateFields } = form;
    const isFirstRun = React.useRef(true);
    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const [iniData, setIniData] = React.useState([]);
    const [workTime, setWorkTime] = React.useState('小时 (0天0小时0分钟)');
    const [timeMode, setTimeMode] = React.useState('date');
    const [timeDate, setTimeDate] = React.useState('');
    const [auditName, setAuditName] = React.useState('');
    const [launchName, setLaunchName] = React.useState('');
    const handleTime = value => {
        setTimeDate(value.format(timeMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'));
    };
    const handleTimePanel = (value, mode) => {
        setTimeMode(mode);
    };

    const handleTimeChange = (date, dateString) => {
        if (!dateString) {
            setTimeDate('');
        }
    };
    const sbTimeTwo = time => {
        if (time) {
            return `${TimeFormatHour(time)} ${time ? '(' : ''}${TimeFormat(time)}${time ? ')' : ''}`;
        }
        return '0小时（0天0小时0分钟）';
    };
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            const {
                applyPlanEndTime,
                applyEstimateWorkDuration,
                delayType,
                delayReason,
                resourceRelation = { uploadResourceFile: '' }
            } = values;
            const { uploadResourceFile = '' } = resourceRelation;
            setConfirmLoading(true);
            delayTask({
                taskId: id,
                delayType,
                applyPlanEndTime:
                    timeDate ||
                    (applyPlanEndTime &&
                        applyPlanEndTime.format(timeMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss')),
                applyEstimateWorkDuration: applyEstimateWorkDuration && applyEstimateWorkDuration * 60,
                planEndTime: iniData.planEndTime || null,
                estimateWorkDuration: iniData.estimateWorkDuration || null,
                delayReason,
                resourceRelation: uploadResourceFile ? [uploadResourceFile] : []
            })
                .then(res => {
                    const { code } = res;
                    if (code !== 10000) {
                        message.error(res.msg);
                        return;
                    }
                    if (code === 10000) {
                        if (onOk) onOk();
                        setVisible(false);
                        message.success(res.msg);
                    }
                })
                .finally(() => {
                    setConfirmLoading(false);
                });
        });
    };
    const handleDelayDetail = () => {
        delayTaskDetail(id).then(res => {
            const { code } = res;
            if (code === 10000) {
                const { auditEmployeeName, launchEmployeeName } = res.data;
                setIniData(res.data);
                if (auditEmployeeName) {
                    setAuditName(auditEmployeeName);
                } else {
                    setAuditName('');
                }
                if (launchEmployeeName) {
                    setLaunchName(launchEmployeeName);
                } else {
                    setLaunchName('');
                }
            }
        });
    };
    // 计算每日工作时长
    React.useEffect(() => {
        // 第一次不运行;
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }

        const time = form.getFieldValue('applyEstimateWorkDuration');
        const newTime = time * 60;
        setWorkTime(TimeFormatForm(newTime));
    }, [JSON.stringify(form.getFieldValue('applyEstimateWorkDuration'))]);

    React.useEffect(() => {
        handleDelayDetail();
    }, []);
    return (
        <Modal
            {...MODAL_DEFAULT_PARAM}
            title="延期"
            width={720}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            wrapClassName={styles.miniMarginBottom}
            onCancel={() => setVisible(false)}
            {...MODAL_FORCE_PARAM}
        >
            <Form {...FORM_DEFAULT_LAYOUT} labelCol={{ span: 6 }}>
                {auditName && <Form.Item label="温馨提示">确定后，需由审核人【{auditName}】通过后方可生效</Form.Item>}
                {!auditName && launchName && (
                    <Form.Item label="温馨提示">确定后，需由发起人【{launchName}】通过后方可生效</Form.Item>
                )}
                <Form.Item label="延期类型">
                    {getFieldDecorator('delayType', {
                        rules: [
                            {
                                required: true,
                                message: '请选择延期类型'
                            }
                        ]
                    })(
                        <Select placeholder="请选择" style={{ width: '100%' }}>
                            {[
                                { value: '任务暂停导致', key: 1 },
                                { value: '预估工时不准', key: 2 },
                                { value: '其他优先级插入', key: 3 },
                                { value: '任务变更', key: 4 },
                                { value: '任务理解偏差', key: 5 },
                                { value: '其他', key: 99 }
                            ].map(item => (
                                <Option key={item.key} value={item.key}>
                                    {item.value}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="原截止时间" className={styles.disabledItem}>
                    {iniData.planEndTime &&
                    iniData.planEndTime.indexOf('00:00:00') === -1 &&
                    iniData.planEndTime.indexOf('23:59:59') === -1
                        ? moment(iniData.planEndTime).format('YYYY-MM-DD HH:mm')
                        : moment(iniData.planEndTime).format('YYYY-MM-DD')}{' '}
                </Form.Item>
                <Form.Item label="申请新截止时间">
                    {getFieldDecorator('applyPlanEndTime', {
                        initialValue: null,
                        rules: [
                            {
                                required: true,
                                message: '请输入申请新截止时间'
                            },
                            {
                                validator(_, value, callback) {
                                    if (value && iniData.planStartTime) {
                                        const startTime =
                                            iniData.planStartTime.indexOf('00:00:00') === -1
                                                ? moment(iniData.planStartTime).format('YYYY-MM-DD HH:mm')
                                                : moment(iniData.planStartTime).format('YYYY-MM-DD');
                                        const newValue = value;
                                        if (iniData.planStartTime && moment(newValue) < moment(iniData.planStartTime)) {
                                            return callback(`不可小于开始时间${startTime}`);
                                        }
                                        return callback();
                                    }
                                    return callback();
                                }
                            }
                        ]
                    })(
                        <DatePicker
                            showTime
                            style={{ width: '100%' }}
                            placeholder="请输入申请新截止时间"
                            onOk={e => handleTime(e, 'start')}
                            onChange={(e1, e2) => handleTimeChange(e1, e2)}
                            onPanelChange={(e1, e2) => handleTimePanel(e1, e2)}
                            allowClear
                            format={timeMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm'}
                        />
                    )}
                </Form.Item>
                {/* 返回分钟 */}
                <Form.Item label="原预估工时" className={styles.disabledItem}>
                    {sbTimeTwo(iniData.estimateWorkDuration)}
                </Form.Item>
                <Form.Item label="申请新预估工时">
                    {getFieldDecorator('applyEstimateWorkDuration')(
                        <InputNumber
                            min={0}
                            max={9999.9}
                            placeholder="请输入申请新预估工时"
                            precision={1}
                            formatter={value => `${value}`.replace('.0', '')}
                            style={{ width: 200 }}
                        />
                    )}
                    &nbsp;&nbsp;&nbsp;&nbsp;{workTime}
                </Form.Item>
                <Form.Item label="原因">
                    {getFieldDecorator('delayReason', {
                        rules: [
                            {
                                required: true,
                                message: '请输入原因'
                            }
                        ]
                    })(<LimitedTextArea maxLength={500} rows={6} placeholder="请输入原因" />)}
                </Form.Item>
                <FileFormItem fieldName="resourceRelation" form={form}></FileFormItem>
            </Form>
        </Modal>
    );
};

export default Form.create()(DelayFormModal);
